package com.jhws.sys.appUser.api;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.comm.service.ITblBuildingDimService;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.business.device.bo.DeviceConstant;
import com.jhws.business.owner.bo.OwnerConstant;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.sys.appUser.service.AppUserService;
import com.jhws.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.sys.appUser.bo.TblSipAcountBindings;
import com.jhws.sys.appUser.bo.TblSipAcountDimBo;
import com.jhws.sys.appUser.service.ITblSipAcountDimService;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.sys.appUser.bo.PhotoInfo;
import com.jhws.sys.appUser.bo.UserInfo;
import com.jhws.sys.appUser.bo.UserInfoForApp;
import com.jhws.sys.appUser.bo.UserInfoList;
import com.jhws.common.base.bo.Global;
import com.jhws.core.exception.BizException;
import com.jhws.business.visitor.bo.TblVisitorDimForm;

/**
 * 手机用户服务
 *
 * @author xiaokek
 * @since 2015年11月29日 上午11:00:18
 */
@Controller
@RequestMapping({"/appUser", "/appuserctrl"})
public class AppUserApiV1 {

    @Resource
    protected AppUserService service;

    @Resource
    protected ITblOwnerDimService ITblOwnerDimService;

    @Resource
    protected ITblSipAcountDimService ITblSipAcountDimService;

    @Resource
    protected ITblCommDimService ITblCommDimService;

    @Resource
    protected ITblBuildingDimService IBuildingService;

    @Resource
    private OSSClientService ossClientService;

    /**
     * 修改密码
     */
    @RequestMapping("modifyPassword")
    @ResponseBody
    public void updatePassword(String findPwd, String username, String oldPassword, String newPassword) {
        service.updatePwd(findPwd, username, oldPassword, newPassword);
    }

    @RequestMapping("getUserInfo")
    @ResponseBody
    public JsonRespData getUserInfo(String username, HttpServletResponse response) throws Exception {
        List<TblSipAcountDimBo> tblSipAcountDim = ITblSipAcountDimService
                .findTblSipAcountDimByWhere("where username = '" + username + "'");
        List<TblOwnerDimBo> tblOwnerDimbo = ITblOwnerDimService
                .findTblOwnerDimByWhere("where sip_acount_id = '" + tblSipAcountDim.get(0).getAcountId() + "'");
        UserInfoForApp info = new UserInfoForApp();
        info.setOwnerName(tblOwnerDimbo.get(0).getOwnerName());
        info.setRoomInfo(tblOwnerDimbo.get(0).getRoomInfoNum());
        return new JsonRespData("getUserInfo", 1, info);
    }

    /**
     * 别墅机自动生成帐号，默认密码123456 返回自动生成的帐号
     */
    @RequestMapping({"anon/autoGeneratedAccount", "autoGeneratedAccount"})
    @ResponseBody
    public JsonRespData autoGeneratedAccount() {
        String user;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = new Date();
            Date date2 = formatter.parse("1900-01-01");
            long l = date1.getTime() - date2.getTime();
            user = Long.toString(l, 36);
            int len = user.length();
            for (int i = 0; i < 10 - len; i++) {
                user = "0" + user;
            }
            ITblSipAcountDimService.addSipAccount(user, "123456", "villa", false);
        } catch (Exception e) {
            // TODO: handle exception
            throw new BizException("-1", "autoGeneratedAccount", "生成帐号失败: " + e.toString());
        }
        return new JsonRespData("autoGeneratedAccount", 1, user);
    }

    /**
     * 别墅机绑定帐号
     */
    @RequestMapping("bindAccount")
    @ResponseBody
    public JsonRespData bindAccount(String account, String bindAccount) {

        List<TblSipAcountBindings> list = null;
        list = ITblSipAcountDimService.getBindingsByUser(bindAccount);
        if (ITblSipAcountDimService.isUserExist(bindAccount) == null) {
            throw new BizException("-1", "bindAccount", "绑定帐号失败: 绑定帐号不存在！");
        } else {
            for (TblSipAcountBindings binding : list) {
                if (account.equals(binding.getBinding())) {
                    throw new BizException("-1", "bindAccount", "绑定帐号失败: 帐号已绑定");
                }
            }
        }
        ITblSipAcountDimService.addSipBinding(bindAccount, account, Global.BINDING_TYPE_VILLA, 0);
        return new JsonRespData("bindAccount", 1, bindAccount);
    }

    /**
     * 获取用户名下所有绑定列表
     */
    @RequestMapping("getUserInfoList")
    @ResponseBody
    public JsonRespData getUserInfoList(String username) throws Exception {
        List<TblSipAcountBindings> list = ITblSipAcountDimService.getBindingsByUser(username);
        if (list == null || list.size() <= 0) {
            throw new BizException("-1", "getAllBindingList", "还没有绑定任何物业！");
        }

        // 是否保存过别墅类型，别墅只保存一条记录
        boolean isSaveVILLA_TYPE = false;
        UserInfoList userInfoList = new UserInfoList();
        UserInfo userInfo;
        List<TblSipAcountBindings> unlockList = new ArrayList<TblSipAcountBindings>();
        List<UserInfo> uList = new ArrayList<UserInfo>();
        for (TblSipAcountBindings tblSipAcountBindings : list) {
            String sipNum = tblSipAcountBindings.getBinding();
            int devicesType = AccountsUtils.devicesType(sipNum);
            if (devicesType == DeviceConstant.OUTDOOR_TYPE || devicesType == DeviceConstant.VILLA_TYPE) {
                unlockList.add(tblSipAcountBindings);
                if (devicesType == DeviceConstant.VILLA_TYPE && !isSaveVILLA_TYPE) {
                    isSaveVILLA_TYPE = true;
                    userInfo = new UserInfo();
                    userInfo.setApplyType(OwnerConstant.OWNER_TYPE_FAMILY);
                    userInfo.setBindingRoom(tblSipAcountBindings.getBinding());
                    userInfo.setCommCode("0000");
                    userInfo.setCommName("别墅");
                    userInfo.setUserType(DeviceConstant.VILLA_TYPE);
                    uList.add(userInfo);
                }
            } else if (devicesType == DeviceConstant.INDOOR_TYPE) {
                TblOwnerDimBo tblOwnerDimBo = ITblOwnerDimService.findTblOwnerDimByMobOrRoomInfo(username,
                        tblSipAcountBindings.getBinding());

                if (tblOwnerDimBo != null) {
                    userInfo = new UserInfo();
                    userInfo.setApplyType(tblOwnerDimBo.getApplyType());
                    userInfo.setBindingRoom(tblSipAcountBindings.getBinding());
                    userInfo.setCommCode(tblOwnerDimBo.getCommCode());
                    userInfo.setCommName(tblOwnerDimBo.getCommName());
                    userInfo.setUserType(DeviceConstant.INDOOR_TYPE);
                    uList.add(userInfo);

                    unlockList.addAll(ITblSipAcountDimService.genDefaultSipUnlockMonitorBindingList(username,
                            tblSipAcountBindings.getBinding()));
                }
            } else if (devicesType == DeviceConstant.MANAGE_TYPE) {
                String commCode = tblSipAcountBindings.getBinding().substring(0, 4);
                TblCommDimBo tblCommDimBo = ITblCommDimService.findTblCommDimById(commCode);
                if (tblCommDimBo != null) {
                    userInfo = new UserInfo();
                    userInfo.setApplyType(OwnerConstant.OWNER_TYPE);
                    userInfo.setBindingRoom(tblSipAcountBindings.getBinding());
                    userInfo.setCommCode(tblCommDimBo.getCommCode());
                    userInfo.setCommName(tblCommDimBo.getCommName());
                    userInfo.setUserType(DeviceConstant.MANAGE_TYPE);
                    uList.add(userInfo);
                }
            }
        }

        userInfoList.setUnlockList(unlockList);
        userInfoList.setUserInfoList(uList);
        return new JsonRespData("getAllBindingList", 1, userInfoList);
    }

    /**
     * 获取绑定列表
     */
    @RequestMapping("getBindingList")
    @ResponseBody
    public JsonRespData getBindingList(String binding, String binding_type) {
        List<TblSipAcountBindings> list = null;
        list = ITblSipAcountDimService.findBindingsByBindingOrType(binding, binding_type);
        if (list == null || list.size() <= 0) {
            throw new BizException("-1", "getBindingList", "此设备没有绑定客户端！");
        }
        return new JsonRespData("getBindingList", 1, list);
    }

    /**
     * 根据用户名及绑定对象删除绑定关系
     */
    @RequestMapping("removeBindingByUserOrBinding")
    @ResponseBody
    public JsonRespData removeBindingByUserOrBinding(String username, String binding) {
        ITblSipAcountDimService.removeSipBinding(username, binding);
        return new JsonRespData("removeBindingByUserOrBinding", 1, "解除绑定成功");
    }

    /**
     * 注册帐号
     *
     * @param username
     * @param password
     */
    @RequestMapping({"registerAccount", "registeredAccount"})
    @ResponseBody
    public JsonRespData registerAccount(String username, String password) {
        service.addAccount(username, password);
        return new JsonRespData("registerAccount", 1, "注册成功");
    }

    /**
     * 是否为绑定关系
     *
     * @param username
     * @param devicesAccount
     */
    @RequestMapping("isBindingAccount")
    @ResponseBody
    public JsonRespData isBindingAccount(String username, String devicesAccount) {
        List<TblSipAcountBindings> list;
        try {
            list = ITblSipAcountDimService.findTblSipAcountBindingsByWhere(
                    "where username = '" + username + "' and binding = '" + devicesAccount + "'");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "isBindingAccount", "获取失败: " + e.toString());
        }

        if (list == null || list.size() <= 0) {
            throw new BizException("-1", "isBindingAccount", "该手机未绑定此设备！");
        }

        return new JsonRespData("isBindingAccount", 1, true);
    }

    /**
     * 申请成为业主,带ed是指为兼容老版本
     */
    @RequestMapping({"registerOwner", "registeredOwner"})
    @ResponseBody
    public JsonRespData registerOwner(String ownerName, String commCode, String ownerMob, String areaCode,
                                      String buildingCode, String roomCode, Long lastModify) throws Exception {
        TblOwnerDimBo bo = new TblOwnerDimBo();
        List<TblOwnerDimBo> ownlist = null;
        List<TblSipAcountDimBo> list = null;
        try {
            list = ITblSipAcountDimService.findTblSipAcountDimByWhere("where username = '" + ownerMob + "'");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "registerOwner", "申请失败: " + e.toString());
        }

        if (null == list || list.isEmpty()) {
            throw new BizException("-1", "registerOwner", "该手机未注册！");
        }

        areaCode = AccountsUtils.appendZeroBuilding(areaCode);
        buildingCode = AccountsUtils.appendZeroBuilding(buildingCode);

        String roomInfo = "";
        TblCommDimBo tblCommDimBo = ITblCommDimService.findTblCommDimById(commCode);
        if (null != tblCommDimBo) {
            bo.setCommName(tblCommDimBo.getCommName());
            roomInfo += "[" + tblCommDimBo.getCommName() + "]" + " ";
        }
        String unitCode = roomCode.substring(0, 2);
        String roomId = roomCode.substring(2, 4);

        String areaAliasName = IBuildingService.getBuildingAliasName(commCode, areaCode, buildingCode);
        String buildingAliasName = IBuildingService.getUnitAliasName(commCode, areaCode, buildingCode);
        roomInfo += areaAliasName + " " + buildingAliasName + " " + unitCode + "楼 " + roomId + "房";

        String roomInfoNum = commCode + areaCode + buildingCode + roomCode;
        // 不同的业主不能绑定同一个手机号
        try {
            ownlist = ITblOwnerDimService
                    .findTblOwnerDimByWhere("where owner_mob = '" + ownerMob + "' and comm_code = '" + commCode + "' and room_info_num = '" + roomInfoNum + "'");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "registeredOwner", "申请失败: " + e.toString());
        }

        if (null != ownlist && ownlist.size() > 0) {
            if (ownlist.get(0).getApplyType() == OwnerConstant.OWNER_TYPE_APPLYING)
                return new JsonRespData("", -1, "您已经提交过该物业申请,请耐心等待审核");
            else if (ownlist.get(0).getApplyType() == OwnerConstant.OWNER_TYPE ||
                    ownlist.get(0).getApplyType() == OwnerConstant.OWNER_TYPE_FAMILY ||
                    ownlist.get(0).getApplyType() == OwnerConstant.OWNER_TYPE_RENTER)
                throw new BizException("-1", "registerOwner", "该手机号在本小区已被业主  " + ownlist.get(0).getOwnerName() + " 绑定"
                        + ownlist.get(0).getRoomInfo() + "，请重新输入!");
            else if (ownlist.get(0).getApplyType() == OwnerConstant.OWNER_TYPE_REJECTED)
                ITblOwnerDimService.removeDim(ownlist.get(0).getOwnerCode());
        }

        bo.setApplyType(OwnerConstant.OWNER_TYPE_APPLYING);
        bo.setOwnerName(ownerName);
        bo.setOwnerMob(ownerMob);
        bo.setCommCode(commCode);
        bo.setAreaCode(areaCode);
        bo.setBuildingCode(buildingCode);
        bo.setUnitCode(unitCode);
        bo.setRoomId(roomId);
        bo.setSipAcountId(list.get(0).getAcountId());
        bo.setRoomInfo(roomInfo);
        bo.setOwnerCode(GetId.randomID());
        bo.setRoomInfoNum(roomInfoNum);
        bo.setCommName(tblCommDimBo.getCommName());
        bo.setLastModify(DateUtil.getTimeNowFmtSec());
        bo.setLastModifyTimeStamp(lastModify);
        try {
            ITblOwnerDimService.save(bo);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "registerOwner", "申请失败: " + e.toString());
        }
        return new JsonRespData("registerOwner", 1, "申请成功");
    }

    /**
     * 授权
     */
    @RequestMapping("authorizeOwner")
    @ResponseBody
    public JsonRespData authorizeOwner(String ownerMob, String authorizePhone, String authorizeName, String commCode,
                                       String areaCode, String buildingCode, String roomCode) {
        if (StringUtils.isNotEmpty(commCode)) {
            TblCommDimBo tblCommDimBo = ITblCommDimService.findTblCommDimById(commCode);
            if (tblCommDimBo != null && tblCommDimBo.getPermissionFamilyAuth() != 0) {
                throw new BizException("-1", "authorizeOwner", "请到物业管理处添加家属！");
            } else if (tblCommDimBo == null) {
                throw new BizException("-1", "authorizeOwner", "小区不存在，请确保已经申请业主！");
            }
        } else {
            throw new BizException("-1", "authorizeOwner", "小区编号不能为空！");
        }
        TblOwnerDimBo bo = new TblOwnerDimBo();
        List<TblOwnerDimBo> ownlist = null;
        List<TblSipAcountDimBo> list = null;
        List<TblOwnerDimBo> ownerList = null;
        try {
            ownerList = ITblOwnerDimService
                    .findTblOwnerDimByWhere("where apply_type = '0' and owner_mob = '" + ownerMob + "'");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "authorizeOwner", "授权失败: " + e.toString());
        }

        if (null == ownerList || ownerList.isEmpty()) {
            throw new BizException("-1", "authorizeOwner", "你不是业主，没有权限授权！");
        }

        try {
            list = ITblSipAcountDimService.findTblSipAcountDimByWhere("where username = '" + authorizePhone + "'");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "authorizeOwner", "授权失败: " + e.toString());
        }

        if (null == list || list.isEmpty()) {
            throw new BizException("-1", "authorizeOwner", "被授权手机号码未注册！");
        }

        String roomInfo = "";
        TblCommDimBo tblCommDimBo = ITblCommDimService.findTblCommDimById(commCode);
        if (null != tblCommDimBo) {
            bo.setCommName(tblCommDimBo.getCommName());
            roomInfo += "[" + tblCommDimBo.getCommName() + "]" + " ";
        }
        String unitCode = roomCode.substring(0, 2);
        String roomId = roomCode.substring(2, 4);

        String areaAliasName = IBuildingService.getBuildingAliasName(commCode, areaCode, buildingCode);
        String buildingAliasName = IBuildingService.getUnitAliasName(commCode, areaCode, buildingCode);

        roomInfo += areaAliasName + " " + buildingAliasName + " " + unitCode + "楼 " + roomId + "房";

        // 不同的业主不能绑定同一个手机号
        try {
            ownlist = ITblOwnerDimService.findTblOwnerDimByWhere(
                    "where owner_mob = '" + authorizePhone + "' and comm_code = '" + commCode + "'");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "authorizeOwner", "授权失败: " + e.toString());
        }
        if (null != ownlist && ownlist.size() > 0) {
            throw new BizException("-1", "authorizeOwner", "该手机号在本小区已被业主  " + ownlist.get(0).getOwnerName() + " 绑定"
                    + ownlist.get(0).getRoomInfo() + "，请重新输入!");
        }
        TblSipAcountDimBo tblSipAcountDimBo = list.get(0);
        String roomInfoNum = commCode + areaCode + buildingCode + roomCode;
        bo.setApplyType(OwnerConstant.OWNER_TYPE_FAMILY);
        bo.setOwnerName(authorizeName);
        bo.setOwnerMob(authorizePhone);
        bo.setCommCode(commCode);
        bo.setAreaCode(areaCode);
        bo.setBuildingCode(buildingCode);
        bo.setUnitCode(unitCode);
        bo.setRoomId(roomId);
        bo.setSipAcountId(tblSipAcountDimBo.getAcountId());
        bo.setRoomInfo(roomInfo);
        bo.setOwnerCode(GetId.randomID());
        bo.setRoomInfoNum(roomInfoNum);
        bo.setCommName(tblCommDimBo.getCommName());
        bo.setLastModify(DateUtil.getTimeNowFmtSec());
        try {
            ITblOwnerDimService.save(bo);
            ITblSipAcountDimService.save(tblSipAcountDimBo);
            ITblSipAcountDimService.addSipBinding(tblSipAcountDimBo.getUsername(), roomInfoNum,
                    Global.BINDING_TYPE_INDOOR, 0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BizException("-1", "authorizeOwner", "授权失败: " + e.toString());
        }
        return new JsonRespData("authorizeOwner", 1, "授权成功");
    }

    /**
     * 获取用户呼叫照片列表
     */
    @RequestMapping("getUserPhotoList")
    @ResponseBody
    public JsonRespData getUserPhotoList(String username, int week) throws Exception {
        List<String> dates = DateUtil.getTheAweek(week);
        List<PhotoInfo> photoInfos = new ArrayList<PhotoInfo>();
        List<TblSipAcountBindings> list;
        list = ITblSipAcountDimService.getBindingsByUser(username);

        List<String> bindingIndoors = new ArrayList<String>();
        List<String> bindingManages = new ArrayList<String>();
        List<String> bindingOutdoors = new ArrayList<String>();
        List<String> bindingWalls = new ArrayList<String>();
        List<String> bindingVillas = new ArrayList<String>();

        for (TblSipAcountBindings tblSipAcountBindings : list) {
            int type = AccountsUtils.devicesType(tblSipAcountBindings.getBinding());
            if (type == DeviceConstant.INDOOR_TYPE) {
                bindingIndoors.add(tblSipAcountBindings.getBinding());
            } else if (type == DeviceConstant.MANAGE_TYPE) {
                bindingManages.add(tblSipAcountBindings.getBinding());
            } else if (type == DeviceConstant.OUTDOOR_TYPE) {
                bindingOutdoors.add(tblSipAcountBindings.getBinding());
            } else if (type == DeviceConstant.WALL_TYPE) {
                bindingWalls.add(tblSipAcountBindings.getBinding());
            } else if (type == DeviceConstant.VILLA_TYPE) {
                bindingVillas.add(tblSipAcountBindings.getBinding());
            }
        }

        StringBuilder path = null;
        PhotoInfo photoInfo = null;
        for (String bindingIndoor : bindingIndoors) {
            String comm = bindingIndoor.substring(0, 4);
            for (String bindingOutdoor : bindingOutdoors) {
                for (String date : dates) {
                    path = new StringBuilder(comm);
                    path.append("/").append("outdoor").append("/").append(date).append("/").append(bindingOutdoor)
                            .append("/").append(bindingIndoor);
                    List<TblVisitorDimForm> tblVisitorDimForms = ossClientService.getVisitor(path.toString());
                    for (TblVisitorDimForm tblVisitorDimForm : tblVisitorDimForms) {
                        photoInfo = new PhotoInfo();
                        String name = tblVisitorDimForm.getVisiImg();
                        photoInfo.setCallAccounts(bindingOutdoor);
                        photoInfo.setUrl(tblVisitorDimForm.getImgUrl());
                        photoInfo.setDate(name.substring(0, name.lastIndexOf(".")));
                        photoInfos.add(photoInfo);
                    }
                }
            }

            for (String bindingWall : bindingWalls) {
                for (String date : dates) {
                    path = new StringBuilder(comm);
                    path.append("/").append("outdoor").append("/").append(date).append("/").append(bindingWall)
                            .append("/").append(bindingIndoor);
                    List<TblVisitorDimForm> tblVisitorDimForms = ossClientService.getVisitor(path.toString());
                    for (TblVisitorDimForm tblVisitorDimForm : tblVisitorDimForms) {
                        photoInfo = new PhotoInfo();
                        String name = tblVisitorDimForm.getVisiImg();
                        photoInfo.setCallAccounts(bindingWall);
                        photoInfo.setUrl(tblVisitorDimForm.getImgUrl());
                        photoInfo.setDate(name.substring(0, name.lastIndexOf(".")));
                        photoInfos.add(photoInfo);
                    }
                }
            }
        }

        for (String bindingVilla : bindingVillas) {
            for (String date : dates) {
                path = new StringBuilder("villa/villa/");
                path.append(date).append("/").append(bindingVilla);
                List<TblVisitorDimForm> tblVisitorDimForms = ossClientService.getVisitor(path.toString());
                for (TblVisitorDimForm tblVisitorDimForm : tblVisitorDimForms) {
                    photoInfo = new PhotoInfo();
                    String name = tblVisitorDimForm.getVisiImg();
                    photoInfo.setCallAccounts(bindingVilla);
                    photoInfo.setUrl(tblVisitorDimForm.getImgUrl());
                    photoInfo.setDate(name.substring(0, name.lastIndexOf(".")));
                    photoInfos.add(photoInfo);
                }
            }
        }
        return new JsonRespData("getUserPhotoList", 1, photoInfos);
    }
}
